import utils.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author ZCR
 * @create 2025/9/7 09:14
 */
public class Solution958 {
    public boolean isCompleteTree(TreeNode root) {
        if (root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int firstPos = -1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (firstPos == -1 && node == null) {
                    firstPos = i;
                }
                if (firstPos != -1 && node != null) {
                    return false;
                }
                if (node != null) {
                    queue.offer(node.left);
                    queue.offer(node.right);
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Solution958 solution = new Solution958();
        TreeNode root = TreeNode.buildTree(new int[]{1, 2, 3, 4, 5, 6});
        System.out.println(solution.isCompleteTree(root));
        root = TreeNode.buildTree(new int[]{1, 2, 3, 4, 5, -1, 7}, -1);
        System.out.println(solution.isCompleteTree(root));
        root = TreeNode.buildTree(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, -1, -1, 15}, -1);//true
        System.out.println(solution.isCompleteTree(root));
    }
}
